package com.zhiwang.planet.ui.adapter

import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.zhiwang.planet.R
import com.zhiwang.planet.mvvm.model.entity.main.GameItem
import com.zhiwang.planet.ui.WebViewActivity

class GameAdapter : RecyclerView.Adapter<GameAdapter.GameItemHolder>() {

    val datas: ArrayList<GameItem> = ArrayList(4)
    var layoutInflater: LayoutInflater? = null
    var reyclerView: RecyclerView? = null

    fun setDatas(outerDatas: List<GameItem>) {
        datas.clear()
        datas.addAll(outerDatas)
        notifyDataSetChanged()
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): GameItemHolder {
        if (layoutInflater == null) layoutInflater = LayoutInflater.from(parent.context)
        if (parent is RecyclerView) reyclerView = parent

        return GameItemHolder(layoutInflater!!.inflate(R.layout.item_game, parent, false))
    }

    override fun getItemCount() = datas.size

    override fun onBindViewHolder(holder: GameItemHolder, position: Int) {
        holder.bind()
    }


    val itemClickListener = View.OnClickListener {

        reyclerView?.apply {
            val pos = getChildViewHolder(it).adapterPosition
            if (TextUtils.isEmpty(datas[pos].url)) return@apply
            if (datas[pos].fullScreen == 1)
                WebViewActivity.loadImmersive(it.context, datas[pos].url!!)
            else
                WebViewActivity.load(it.context, datas[pos].url!!)
        }
    }

    inner class GameItemHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {

        var icon = itemView.findViewById<ImageView>(R.id.game_icon)
//        var gameName = itemView.findViewById<TextView>(R.id.game_name)

        fun bind() {
            itemView.setOnClickListener(itemClickListener)
            val gameItem = datas[adapterPosition]
            val iconUrl = gameItem.iconUrl
            if (TextUtils.isEmpty(iconUrl)) {
                Glide.with(itemView.context)
                        .load(R.drawable.ic_qq28)
                        .into(icon)
            } else {
                Glide.with(itemView.context)
                        .load(iconUrl)
                        .into(icon)
            }

//            gameName.text = gameItem.name

        }

    }
}